<template>
  <div>
    <Upload :action="imgAction"
            :headers="header"
            :before-upload="uploadImg">
      <Button :type="type"
              icon="ios-cloud-upload-outline">{{text}}</Button>
    </Upload>
    <div style="width:100%;"
         class="url primary"
         v-if="imgName">上传成功：{{imgName}}</div>
  </div>
</template>

<script>
export default {
  name: 'upload-img',
  props: {
    url: {
      type: String,
      default: function () {
        return this.imgUrl + localStorage.access_token + '/uid/' + localStorage.uid
      }
    },
    text: {
      type: String,
      default: '上传图片'
    },
    type: {
      type: String,
      default: 'default'
    }
  },
  data () {
    return {
      uploadFlag: false,
      imgName: '',
      imgAction: '',
      header: { 'Content-Type': 'multipart/form-data' }
    }
  },
  methods: {
    uploadImg (file) {
      let formData = new FormData()
      let imgU = file
      let url = this.url
      formData.append('image', imgU)
      let config = {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }
      this.http.post(url, formData, config).then((response) => {
        this.imgName = response.data.data[0]
        this.$emit('getUrl', this.imgName)
      })
      return false
    }
  }
}
</script>

<style scoped>
.url {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
